package com.wwk.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wwk.dao.CheckGroupDao;
import com.wwk.entity.PageResult;
import com.wwk.entity.QueryPageBean;
import com.wwk.pojo.CheckGroup;
import com.wwk.pojo.CheckItem;
import com.wwk.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname CheckGroupServiceImpl
 * @Description TODO
 * @Date 2020/10/31 19:21
 * @Created by com.wwk
 * @Author com.wwk
 */
@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupDao groupDao;
    @Override
    public PageResult findPage(QueryPageBean pageBean) {
        //使用pagehelper来分页,紧接着的查询即是分页
        PageHelper.startPage(pageBean.getCurrentPage(), pageBean.getPageSize());
        final Page<CheckGroup> groupByCondition = groupDao.findGroupByCondition(pageBean.getQueryString());
        return new PageResult(groupByCondition.getTotal(),groupByCondition.getResult());
    }

    @Override
    public List<CheckItem> findAllItem() {
        return groupDao.findAllItem();
    }

    @Override
    public void add(CheckGroup checkGroup, Integer[] itemIds) {
        //添加检查组合
        groupDao.addGroup(checkGroup);
        //设置检查组合和检查项的关联关系
        //插入时，xml文件中为当前checkGroup找到了刚插入的id，并赋值给当前checkGroup
        setCheckGroupAndCheckItem(checkGroup.getId(),itemIds);
    }
    public void setCheckGroupAndCheckItem(Integer groupId,Integer[] itemIds){

        Map<String,Integer> map=null;
        if(itemIds!=null&&itemIds.length>0){
            for (Integer id: itemIds ) {
                map=new HashMap<>();
                map.put("checkgroup_id",groupId);
                map.put("checkitem_id",id);
                groupDao.addGroupItems(map);
            }
        }
    }

    @Override
    public CheckGroup findById(Integer groupId) {
        return groupDao.findById(groupId);
    }

    @Override
    public void deleteById(Integer groupId) {
        //先删除检查组合检查项的多对多表中的内容，再删除检查组表中的内容
        groupDao.deleteGroupItems(groupId);
        groupDao.deleteById(groupId);
    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //修改检查组的属性，并且修改检查项列表
        groupDao.edit(checkGroup);
        //先删除旧的多对多检查项关系表单的内容
        groupDao.deleteGroupItems(checkGroup.getId());
        //再重新添加
        setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);
    }

    @Override
    public List<Integer> findAllGroupItemIds(Integer groupId) {
        return groupDao.findAllGroupItemIds(groupId);
    }

    @Override
    public List<CheckGroup> findAllForMeal() {
        return groupDao.findAllForMeal();
    }


}
